/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ac.neec.mio.ui.activity;

import ac.neec.core.ble.util.BleUtil;
import ac.neec.listener.EventsCallBackListener;
import ac.neec.listener.HeartRateEventListener;
import ac.neec.mio.R;
import ac.neec.mio.ui.fragment.ConnectBLEFlagment;
import ac.neec.mio.ui.fragment.MeasurementTestFlagment;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

public class MeasurementTestActivity extends BLEActivity implements EventsCallBackListener<Object> {
	public static final String BACK_STACK_BLE_CONNECT_ADD = "BLE Connect Setting ADD";
	public static final String BACK_STACK_MEASUREMENT_TEST_FRAGMENT_ADD = "MeasurementTestFragment ADD";
	public static final int CALLBACK_ID_CONNECT_BLE_FRAGMENT = 10;
	public static final int CALLBACK_ID_MEASUREMENT_START = 11;
	public static final int CALLBACK_ID_MEASUREMENT_STOP = 12;
	private static final int REQUEST_ENABLE_BLUETOOTH = 0;
	private HeartRateEventListener<Object> mEventListener;
	private BluetoothDevice device;
	private boolean actFlag = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_measurement_test);

		startupBluetooth();
		setupOnCreate();
	}

	private void startupBluetooth() {
		//      TODO BLE Support check
		if (!BleUtil.isBLESupported(this)) {
			Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
			finish();
		}
		BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
		if (btAdapter == null) {
			//         alertBluetoothUnsupported();
		} else {
			if (!btAdapter.isEnabled()) {
				Intent intent = new Intent(
						BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(intent, REQUEST_ENABLE_BLUETOOTH);
			}
			else {
				startupConnectBLEFragment();
			}
		}
	}

	private void startupConnectBLEFragment() {
		ConnectBLEFlagment fragment = new ConnectBLEFlagment();
		FragmentTransaction transaction = getFragmentManager().beginTransaction();
		transaction.add(R.id.act_measurement_test_container, fragment);
		transaction.addToBackStack(BACK_STACK_BLE_CONNECT_ADD);
		transaction.commit();

	}

	private void startupTestMeasurement(BluetoothDevice device) {
		//TODO Connect BLE Device
		this.device = device;
		setupBLEConnect(device, this);

	}

	@Override
	protected void onResume() {
		super.onResume();
		setupOnResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		setupOnPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		setupOnDestroy();
	}

	@Override
	protected void onActivityResult(int requestCode, int ResultCode, Intent date) {
		if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
			if (ResultCode == Activity.RESULT_OK) {
				startupConnectBLEFragment();
			} else {
				//alertBluetoothUnAccept();
				//TODO
				Toast.makeText(getApplicationContext(), "Bluetooth unactive", Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	protected void updateConnectionState(int resourceId) {

	}

	@Override
	protected void clearUI() {

	}

	@Override
	protected void displayData(String data) {
		if (mEventListener == null) {
			Log.e("EventListener", "null pointer");
		}
		else {
			mEventListener.notifyHeartRateEvent(data);
		}
	}

	@Override
	public void onCallBack(int id, Object value) {
		switch (id) {
		case CALLBACK_ID_CONNECT_BLE_FRAGMENT:
			BluetoothDevice device = (BluetoothDevice) value;
			startupTestMeasurement(device);
			break;
		case CALLBACK_ID_MEASUREMENT_START:
			setupReadCharacteristic();
			setupOnResume();
			break;
		case CALLBACK_ID_MEASUREMENT_STOP:
			finish();
			break;
		}
	}

	@Override
	protected void notifyServiceConnecttion(boolean flag) {
		if (flag == false)
			return;
		setupOnCreate();
		//		setupReadCharacteristic();
		MeasurementTestFlagment fragment = new MeasurementTestFlagment();
		try {
			mEventListener = (HeartRateEventListener) fragment;
		} catch (ClassCastException e) {
			throw new ClassCastException(fragment.toString() + " must implement OnArticleSelectedListener");
		}
		setupOnCreate();
		Bundle bundle = new Bundle();
		bundle.putSerializable("deviceName", device.getName());
		bundle.putSerializable("deviceAddr", device.getAddress());
		fragment.setArguments(bundle);
		FragmentTransaction transaction = getFragmentManager().beginTransaction();
		transaction.replace(R.id.act_measurement_test_container, fragment);
		transaction.addToBackStack(BACK_STACK_MEASUREMENT_TEST_FRAGMENT_ADD);
		transaction.commit();
		actFlag = true;
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		// Backボタン検知
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			if (actFlag)
				onCallBack(CALLBACK_ID_MEASUREMENT_STOP, null);
			return false;
		}
		return super.dispatchKeyEvent(event);
	}

}
